const fs = require("fs");
const path = require("path"); //使用定位模块转换为绝对定位
const format = require(path.resolve("./format"))();
const formatStr = "yyyy-MM-dd HH:mm:ss";
const filePath = path.resolve("../mongoExport");
const db = require(path.resolve("./mongodb"));
const config = require(path.resolve("./mongodb.config"));
const jd = config.jd;
const limit = 7; //保留的文件数

let retrech = async () => {
  let start = new Date();
  let logId = Number(start);
  try {
    await db.insertOne(jd.log, {
      operation: "delete", //清理文件夹
      logId: logId,
      start: start.format(formatStr),
    });
    let names = fs.readdirSync(filePath);
    let dirs = [];
    //遍历内容，获取文件/文件夹信息
    for (let name of names) {
      let _p = `${filePath}/${name}`;
      let _s = fs.statSync(_p);
      if (_s.isDirectory()) {
        let _i = {
          path: _p,
          birth: _s.birthtimeMs,
        };
        dirs.push(_i);
      }
    }
    let logger = {};
    if (dirs.length  > 7) 
    {
      dirs.sort((a, b) => {
        return a.birth - b.birth;
      });//排序
      dirs.length = dirs.length - limit;//按序去掉最新的n个文件夹
      for (let dir of dirs) {
        let inside = fs.readdirSync(dir.path);//本来需要递归删除文件夹，但这里确定文件夹内只有一层内容，就直接删了，如果文件夹格式修改了，可能会报错
        if (inside.length > 0) {
          for (let _fileName of inside) {
            fs.unlinkSync(`${dir.path}/${_fileName}`);
          }
        }
        fs.rmdirSync(dir.path);
      }
      logger.removed = dirs.map((item) => {
        return item.path;
      });//记录已经删除的文件夹
    }
    logger.end = new Date().format(formatStr);
    await db.updateMany(jd.log, { logId: logId }, logger);
  } catch (error) {
    await db.insertOne(jd.error, {
      logId: logId,
      error: error,
      stack: error.stack,
    });
  }
};

module.exports = retrech;
